<template>
  <div class="page-wrap mb10">
    <Alert type="warning" show-icon
      >提示：本步骤是对模板中的设备进行编辑，操作步骤：部署环境 >
      进入虚拟机(操作) > 关机 > 生成镜像 > 设置接入机器 >
      保存，如不需要则点击“下一步”继续即可
    </Alert>
    <!-- <WarningTip placement="right">
            <p>本步骤是对模板中的设备进行编辑，如不需要则点击“下一步”继续即可，操作步骤如下：</p>
            <p>1、部署环境</p>
            <p>2、进入虚拟机(操作)</p>
            <p>3、关机</p>
            <p>4、生成镜像</p>
            <p>5、设置接入机器</p>
            <p>6、保存</p>
        </WarningTip> -->
    <!-- <Steps :current="step" class="mt10 mb10">
            <Step title="开始"></Step>
            <Step title="部署"></Step>
            <Step title="生成镜像"></Step>
            <Step title="完成"></Step>
        </Steps> -->
    <div class="controlBtn flex-between">
      <div class="flex">
        <Button
          type="primary"
          @click="deployExper()"
          :loading="creatLoading"
          :disabled="deployStatus == 3"
          class="mt10 mb10"
          >{{ createdVmText }}</Button
        >
        <Icon
          type="ios-alert-outline"
          class="deployErrorBtn ml10"
          title="点击查看错误详情"
          @click="getProjectDeployDetail"
          v-if="createdVmText == '重新部署' || errorMessage"
          style="font-size: 24px; color: #ed4014"
        />
        <Poptip
          confirm
          title="确定要销毁课件吗？"
          @on-ok="destroyExper()"
          class="ml10"
        >
          <Button type="error" v-show="destroyStatus">销毁课件</Button>
        </Poptip>
      </div>
      <div class="flex">
        <span
          class="destoryTime mr10"
          v-if="destroyStatus && proId && leftTime > 0"
          >环境销毁倒计时：{{ curTime.h }}:{{ curTime.m }}:{{ curTime.s }}</span
        >
        <Poptip
          confirm
          title="每次延长时间为24个小时，确认延长销毁时间?"
          @on-ok="extendDestroyTime"
          v-if="destroyStatus && proId && leftTime > 0"
          transfer
          word-wrap
          width="200"
        >
          <Button type="primary">延长销毁时间</Button>
        </Poptip>
      </div>
    </div>
    <Progress
      :percent="deployProcess"
      :stroke-width="16"
      text-inside
      v-if="deployStatus == 9"
    >
      <Icon type="checkmark-circled"></Icon>
      <span>{{ processText }}</span>
    </Progress>
    <EnvironManage
      :prjId="proId"
      :ecId="ecId"
      :ecName="ecName"
      v-if="proId && deployStatus == 3"
      @setImageList="getImageList"
      @setAccess="setAccess"
    ></EnvironManage>
    <ImageList
      ref="imageList"
      :prjId="proId"
      v-if="proId"
      :ecId="ecId"
      style="margin-top: 30px"
      @on-generate-finish="getGenerateImageList"
    ></ImageList>
    <SaveExper
      :ecId="ecId"
      :prjId="proId"
      :envTemplateId="templateId"
      :deployStatus="deployStatus"
      :disabled="generateImageList.length === 0"
      :ecName="ecName"
      :accessName="accessName"
      @setReplaceTotal="getReplaceTotal"
      @getExperStatus="initMounted"
    >
    </SaveExper>
    <Modal
      v-model="deployErrorDetailModal"
      title="环境部署错误详情"
      :width="errorDetailData.length > 0 ? 80 : 20"
      footer-hide
    >
      <h3
        v-if="errorMessage && errorDetailData.length == 0"
        style="color: #ed4014"
      >
        <span v-html="errorMessage">{{ errorMessage }}</span>
      </h3>
      <Table
        :columns="errorDetailColumns"
        :data="errorDetailData"
        v-if="errorDetailData.length > 0"
      ></Table>
    </Modal>
  </div>
</template>
<script>
import encryption from '@/libs/encryption.js';
import {
    destroyExper,
    creatExper,
    experStatus,
    getDestroyTime,
    getProjectDeployDetail,
    extendDestroyTime,
    queryExpDeployProgress,
    getProjectInfo
} from '@/api/selfStudy/courseExp.js';
import EnvironManage from './environManage';
import ImageList from './createImageList';
import SaveExper from './saveExper';
export default {
    components: {
        EnvironManage,
        ImageList,
        SaveExper
    },
    props: ['ecId', 'ecName', 'templateId'],
    data() {
        return {
            // 用户信息
            //userName:'',
            USER_ID: '',
            //部署信息
            proId: '', //工程id
            deployProcess: 0, //部署进度
            deployStatus: 0, //部署状态
            processText: '',
            creatLoading: false, //部署按钮loading
            btnType: 'primary', //部署按钮类型
            createdVmText: '部署环境', //部署按钮显示
            //销毁
            destroyLoading: false, //销毁按钮loading
            destroyStatus: false, //销毁状态
            //定时器
            queryStatus: '',
            destroyInterval: '',
            //倒计时
            leftTime: 0,
            curTime: {
                h: '00',
                m: '00',
                s: '00'
            },
            //部署错误详情
            deployErrorDetailModal: false,
            errorDetailData: [],
            errorDetailColumns: [
                {
                    key: 'name',
                    title: '名称'
                },
                {
                    key: 'type',
                    title: '类型'
                },
                {
                    key: 'status',
                    title: '状态'
                },
                {
                    key: 'operation',
                    title: '操作'
                },
                {
                    key: 'errorMsg',
                    title: '错误信息'
                }
            ],
            errorMessage: '',
            generateImageList: [], //生成的镜像列表
            replaceTotal: 0, //生成的模板
            accessName: ''
        };
    },
    computed: {
        step() {
            let step = 0;
            if (this.deployStatus === 3) {
                step = 1;
            } else if (this.generateImageList.length > 0) {
                step = 2;
            } else if (this.replaceTotal > 0) {
                step = 3;
            }
            return step;
        }
    },
    created() {
        // 获取用户id
        let November = sessionStorage.getItem('November');
        November = JSON.parse(encryption.SelfUseDecrypt(November));
        this.USER_ID = November.userId;
        this.isRootDesinger = November.isRootDesinger;
    },
    mounted() {
        this.initMounted();
    },
    beforeRouteLeave(to, from, next) {
        if (to.path === '/experiment') {
            //              to.query.page = this.$route.query.page
            next();
        } else {
            next();
        }
    },
    beforeDestroy() {
        clearInterval(this.destroyInterval);
        clearInterval(this.queryStatus);
    },
    methods: {
        initMounted(){
          this.generateImageList=[]
          this.getExperStatus();
        },
        //调用部署接口
        deployExper() {
            let formData = {
                ecId: this.ecId,
                userId: this.USER_ID
            };
            this.creatLoading = true;
            if (this.destroyInterval) {
                clearInterval(this.destroyInterval);
            }
            creatExper(formData)
                .then((res) => {
                    if (res.code === 1) {
                        if (res.attribute.status && res.attribute.status === 3) {
                            this.$Message.info('已有环境部署成功，请先销毁才能部署新的环境');
                        } else {
                            this.proId = res.attribute.projectId;
                            this.queryCreatedStatus();
                        }
                    } else {
                        this.$Message.error({
                            content: res.message,
                            duration: 3
                        });
                        this.creatLoading = false;
                    }
                })
                .catch((err) => {
                    this.creatLoading = false;
                    console.log(err);
                });
        },
        // 查询部署状态
        queryCreatedStatus() {
            this.queryStatus = setInterval(() => {
                queryExpDeployProgress(this.proId)
                    .then((res) => {
                        if (res.code == 1) {
                            this.processText = '部署中...' + res.attribute.progress + '%';
                            this.deployProcess = res.attribute.progress;
                            this.deployStatus = res.attribute.status;
                            this.$emit('setDeployStatus', this.deployStatus);
                            if (res.attribute.progress === 100 && res.attribute.status === 3) {
                                this.creatLoading = false;
                                // 创建按钮
                                this.createdVmText = '部署成功';
                                this.btnType = 'primary';
                                // 销毁按钮
                                this.destroyStatus = true;
                                this.deployNum = 3;
                                //清除定时查询
                                clearInterval(this.queryStatus);
                                this.$Message.success({
                                    content: '部署成功',
                                    duration: 3
                                });
                                setTimeout(() => {
                                    this.getDestroyTimeInter();
                                }, 3000);
                            } else if (
                                res.attribute.progress === 100 &&
                                res.attribute.status === 6
                            ) {
                                this.creatLoading = false;
                                // 按钮颜色 文字
                                this.btnType = 'primary';
                                this.createdVmText = '重新部署';
                                // 显示销毁按钮
                                this.destroyWidth = '30%';
                                this.destroyStatus = true;
                                this.deployNum = 6;
                                //清除定时查询
                                clearInterval(this.queryStatus);
                            }
                        } else {
                            this.creatLoading = false;
                            // 按钮颜色 文字
                            this.btnType = 'primary';
                            this.createdVmText = '重新部署';
                            // 显示销毁按钮
                            this.destroyStatus = true;
                            this.deployNum = 6;
                            //清除定时查询
                            clearInterval(this.queryStatus);
                            this.$Message.error({
                                content: res.message,
                                duration: 3
                            });
                        }
                        this.getProjectInfo(); //查询错误信息
                    })
                    .catch((err) => {
                        console.log(err);
                    });
            }, 3000);
        },
        // 获取课件的部署状态
        getExperStatus() {
            
            experStatus(this.USER_ID, this.ecId)
                .then((res) => {
                  
                    let status = res.attribute.data.status;
                    this.deployStatus = res.attribute.data.status;
                    this.$emit('setDeployStatus', this.deployStatus);
                    this.proId = res.attribute.data.instanceid;
                    if (this.proId) {
                        this.getProjectInfo();
                    }
                    // 新建   未部署
                 // console.log('获取课件的部署状态-----',status,res)
                    if (status === 0 || status === 10) {
                        // 按钮颜色 文字
                        this.createdVmText = '部署环境';
                        this.destroyStatus = false;
                        this.creatLoading = false;
                        this.destroyLoading = false;
                        this.destroyStatus = false;
                        this.showProgess = false;
                        this.btnType = 'primary';
                    } else if (status === 3) {
                        // 成功
                        // 按钮颜色 文字
                        this.btnType = 'success';
                        this.createdVmText = '部署成功';
                        // 显示销毁按钮
                        this.destroyStatus = true;
                        this.getDestroyTimeInter();
                        this.showProgess = false;
                    } else if (status === 6) {
                        // 失败
                        // 按钮颜色 文字
                        this.btnType = 'primary';
                        this.createdVmText = '重新部署';
                        // 显示销毁按钮
                        this.destroyStatus = true;
                        this.showProgess = false;
                    } else if (status === 9) {
                        // 部署中
                        this.btnType = 'primary';
                        this.createdVmText = '部署中...';
                        this.creatLoading = true;
                        this.queryCreatedStatus();
                    }
                })
                .catch((err) => {
                    console.log(err);
                });
        },
        // 销毁
        destroyExper() {
            destroyExper(this.proId, this.USER_ID)
                .then((res) => {
                    if (res.code == 1) {
                        this.proId = '';
                        this.createdLoad = false;
                        // 创建按钮
                        this.createdVmText = '部署环境';
                        this.btnType = 'primary';
                        // 销毁按钮
                        this.destroyStatus = false;
                        this.$Message.success({
                            content: res.message,
                            duration: 3
                        });
                        this.deployNum = 10;
                        this.processText = '0%';
                        clearInterval(this.destroyInterval);
                        this.getExperStatus();
                        this.generateImageList = [];
                    } else {
                        this.$Message.error(res.message);
                    }
                })
                .catch((err) => {
                    console.log(err);
                });
        },
        //
        getDestroyTimeInter() {
            //              if(!this.destroyInterval){
            clearInterval(this.destroyInterval);
            this.getDestroyTime();
            //一分钟矫正一次销毁时间
            this.destroyInterval = setInterval(() => {
                this.getDestroyTime();
            }, 1000 * 60);
            //              }
        },
        // 获取销毁时间
        getDestroyTime() {
            getDestroyTime(this.proId)
                .then((res) => {
                    if (res.code === 1) {
                        this.leftTime = res.attribute.destroyTime;
                        if (this.leftTime > 0) {
                            this.getTimes();
                        } else {
                            //                                window.close();
                            clearInterval(this.destroyInterval);
                        }
                    }
                })
                .catch((err) => {
                    console.log(err);
                });
        },
        getTimes() {
            clearTimeout(this.timeout);
            let leftTime = this.leftTime;
            if (leftTime > 0) {
                let h = Math.floor(leftTime / 1000 / 60 / 60);
                let m = Math.floor((leftTime / 1000 / 60) % 60);
                let s = Math.floor((leftTime / 1000) % 60);
                this.curTime = {
                    h: h < 10 ? '0' + h : h,
                    m: m < 10 ? '0' + m : m,
                    s: s < 10 ? '0' + s : s
                };
                let _this = this;
                this.timeout = setTimeout(() => {
                    _this.leftTime = _this.leftTime - 1000;
                    _this.getTimes();
                }, 1000);
            } else {
                clearInterval(this.destroyInterval);
            }
        },
        //获取工程部署错误详情
        getProjectInfo() {
            if (!this.proId) {
                return;
            }
            getProjectInfo(this.proId)
                .then((data) => {
                    if (data.code == 1) {
                        let projectInfo = data.data.project;
                        this.projectInfo = data.data.project;
                        this.errorMessage = data.data.project.errorMessage;
                        //									this.getProjectDeployDetail(projectInfo.deployId);
                    } else if (data.code == -2) {
                        this.$Message.error('工程不存在');
                    } else {
                        this.$Message.error(data.message);
                    }
                })
                .catch((error) => {
                    console.log(error);
                });
        },
        getProjectDeployDetail() {
            this.deployErrorDetailModal = true;
            let deployId = this.projectInfo.deployId;
            let params = {
                pageIndex: 1,
                pageSize: 1000,
                status: 400
            };
            getProjectDeployDetail(deployId, params)
                .then((data) => {
                    if (data.code == 1) {
                        this.errorDetailData = data.data.items;
                    } else {
                        this.errorDetailData = [];
                        this.$Message.error(data.message);
                    }
                })
                .catch((error) => {
                    console.log(error);
                });
        },
        getImageList() {
            if (this.proId) {
                this.$refs.imageList.getCreateImageList();
            }
        },
        setAccess(name) {
            this.accessName = name;
        },
        getGenerateImageList(list) {
            this.generateImageList = list;
        },
        getReplaceTotal(total) {
            this.replaceTotal = total;
            if (total > 0) {
                this.$emit('on-finish', true);
            }
        },
        gotoNextStep() {
            // this.$emit('changeStep', 2);
        },
        extendDestroyTime() {
            extendDestroyTime(this.proId)
                .then((data) => {
                    if (data.code == 1) {
                        this.$Message.info(data.message);
                        this.getDestroyTimeInter();
                    } else {
                        this.$Message.error(data.message);
                    }
                })
                .catch((error) => {
                    console.log(error);
                });
        }
    }
};
</script>
<style scoped>
.destoryTime {
  color: #db4747;
  font-weight: 700;
  /* position: absolute; */
  top: 0px;
  right: 30px;
}
.mb10 {
  margin-bottom: 10px;
}
</style>

